package deepseek

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/mcp-office/agent/llm"
	"io"
	"net/http"
)

const (
	DeepseekChatModel        = "deepseek-chat"
	DeepseekReasonerModel    = "deepseek-reasoner"
	ChatMessageRoleSystem    = "system"
	ChatMessageRoleUser      = "user"
	ChatMessageRoleAssistant = "assistant"
)

// DeepSeekProvider 定义结构体
type DeepSeekProvider struct {
	llm.Provider
}

type ModelsResponse struct {
	Object string          `json:"object"`
	Data   []llm.ModelMeta `json:"data"`
}

// NewDeepSeekProvider 创建一个新的实例
// sk-dc046c86a7474018965122f4bec837d5
func NewDeepSeekProvider(apiKey string) *DeepSeekProvider {
	var deepseek DeepSeekProvider
	deepseek.BaseUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1"
	deepseek.ApiKey = apiKey
	return &deepseek
}

func (p *DeepSeekProvider) FetchModels() ([]llm.ModelMeta, error) {
	request, err := llm.NewRequestBuilder(p.ApiKey).
		SetMethod(http.MethodGet).
		SetBaseUrl(p.BaseUrl).
		SetPath("/models").
		SetBody("").
		Build(context.Background())
	if err != nil {
		return nil, err
	}
	resp, err := http.DefaultClient.Do(request)
	if err != nil || resp.StatusCode != http.StatusOK {
		return nil, err
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应体失败: %v", err)
	}
	var result ModelsResponse
	err = json.Unmarshal(body, &result)
	if err != nil {
		fmt.Println("JSON解析错误:", err)
		return nil, err
	}
	return result.Data, nil
}

func (p *DeepSeekProvider) ChatCompletion(ctx context.Context, req llm.ChatCompletionRequest) (string, error) {
	request, err := llm.NewRequestBuilder(p.ApiKey).
		SetMethod(http.MethodPost).
		SetBaseUrl(p.BaseUrl).
		SetPath("/chat/completions").
		SetBody(req).
		Build(ctx)
	if err != nil {
		return "", err
	}
	resp, err := http.DefaultClient.Do(request)
	if err != nil || resp.StatusCode != http.StatusOK {
		return "", err
	}
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("读取响应体失败: %v", err)
	}
	return string(body), nil
}
